package com.jh3502.vivo.function.citylist;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jh3502.vivo.R;
import com.jh3502.vivo.base.BaseActivity;
import com.jh3502.vivo.base.BasePresenter;
import com.jh3502.vivo.view.MyRecyclerView;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;

public class CityListActivity extends BaseActivity {
    @BindView(R.id.city_list)
    MyRecyclerView cityList;
    @BindView(R.id.city_list_search)
    EditText cityListSearch;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    private CityListAdapter cityListAdapter;
    private SQLiteDatabase database;
    private List<CityBean> dataList = new ArrayList<>(2);
    private List<CityBean> dataChosen = new ArrayList<>(2);
    private CityDBManager dbManager;
    private LinearLayoutManager layoutMgr;


    @Override
    public BasePresenter initPresenter() {
        return null;
    }

    @Override
    protected int setViewId() {
        return R.layout.activity_city_list;
    }

    @Override
    protected void initView() {
        toolbar.setTitle("");
        toolbarTitle.setText("选择城市");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        layoutMgr = cityList.getLayoutManager();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;
            default:
        }
        return true;
    }

    @Override
    protected void initData() {
        dbManager = new CityDBManager(this);
        dbManager.openDateBase();
        dbManager.closeDataBase();
        database = SQLiteDatabase.openOrCreateDatabase(CityDBManager.DB_PATH + "/" + CityDBManager.DB_NAME, null);
        database.setLocale(Locale.CHINESE);
        dataList.addAll(getSelectCityNames(""));
        cityListAdapter = new CityListAdapter(this, dataList, dataChosen);
        cityList.setAdapter(cityListAdapter);
        cityListAdapter.setOnItemClickListener(s -> {
            View view = layoutMgr.getChildAt(s - (int) layoutMgr.getChildAt(0).getTag());
            CheckBox itemCityCheck = view.findViewById(R.id.item_city_check);
            itemCityCheck.toggle();
            if (itemCityCheck.isChecked() == true) {
                dataChosen.add(dataList.get(s));
            } else {
                for (Iterator<CityBean> iteratorCity = dataChosen.iterator(); iteratorCity.hasNext(); ) {
                    String cityId = iteratorCity.next().getAdcode();
                    if (cityId.equals(dataList.get(s).getAdcode())) {
                        iteratorCity.remove();
                    }
                }
            }
        });

        cityListSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                dataList.clear();
                dataList.addAll(getSelectCityNames(s.toString()));
                cityListAdapter.notifyDataSetChanged();
            }

            @Override
            public void afterTextChanged(Editable s) {


            }
        });
    }

    @Override
    protected void doOnDestroy() {

    }

    @Override
    protected void doOnResume() {

    }

    @Override
    protected void doOnSaveInstanceState(Bundle savedInstanceState) {

    }


    @Override
    public void responseError(int code, String msg) {

    }


    @OnClick(R.id.city_cancel)
    public void onCityCancelClicked() {

        onBackPressed();
    }

    @OnClick(R.id.city_submit)
    public void onCitySubmitClicked() {
        Intent intent = new Intent();
        String s = new Gson().toJson(dataChosen);
        intent.putExtra("dataChosen", s);
        setResult(Activity.RESULT_OK, intent);
        onBackPressed();
    }

    private List<CityBean> getSelectCityNames(String con) {
        List<CityBean> names = new ArrayList<>();
        Pattern pattern = Pattern.compile("[\\u4e00-\\u9fa5]+");
        Matcher m = pattern.matcher(con);
        String sqlString;
        sqlString = "SELECT * FROM T_city WHERE AllNameSort LIKE " + "\"" + con + "%" + "\"" + " ORDER BY NameSort";
        Cursor cursor = database.rawQuery(sqlString, null);
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToPosition(i);
            CityBean cityBean = new CityBean();
            String s = cursor.getString(cursor.getColumnIndex("AllNameSort"));
            String sortString = cursor.getString(cursor.getColumnIndex("NameSort"));
            cityBean.setName(s);
            cityBean.setNameSort(sortString);
            cityBean.setAdcode(cursor.getString(cursor.getColumnIndex("CityName")));
            names.add(cityBean);
        }
        cursor.close();
        return names;
    }

}